package com.sdp.core.bizc.shiro;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.sdp.core.bizc.utils.CoreConstantsEnum;
import com.sdp.core.bizc.utils.TokenUtils;
import com.sdp.core.bizc.vo.Result;

public class ShiroAuthFilter extends BasicHttpAuthenticationFilter {
	
	protected String getAuthzHeader(ServletRequest request) {
		try {
			HttpServletRequest httpRequest = WebUtils.toHttp(request);
			return httpRequest.getHeader(CoreConstantsEnum.header中的token参数名.getCode());
		} catch (Exception e) {
			return null;
		}
	}
	
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
		
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String method = httpRequest.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }
        String token = this.getAuthzHeader(request);
		if(StringUtils.isEmpty(token)) {
			shiroAuthResponse(response);
			return false;
		}else {
			
			JSONObject obj = TokenUtils.verify(token);
			if(obj==null) {
				shiroAuthResponse(response);
				return false;
			}else if(StringUtils.isEmpty(obj.get(CoreConstantsEnum.token中账号的属性名.getCode())) 
					|| StringUtils.isEmpty(obj.get(CoreConstantsEnum.token中密码的属性名.getCode()))
					|| StringUtils.isEmpty(obj.get(CoreConstantsEnum.token中工号的属性名.getCode()))
					|| StringUtils.isEmpty(obj.get(CoreConstantsEnum.token中姓名的属性名.getCode()))) {
				shiroAuthResponse(response);
				return false;
			}else {
				return true;
			}
			
		}
	
	}

	private void shiroAuthResponse(ServletResponse response) {
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		httpServletResponse.setContentType("application/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        Result<Object> r = new Result<Object>();
		r.setSuccess(false);
		r.setCode("401");
		String jsonString = JSONObject.toJSONString(r);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            out.write(jsonString.getBytes());
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

		
	}
}
